package com.fuershiye.woman.monitor.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.fuershiye.woman.monitor.beans.*;
import com.fuershiye.woman.monitor.constants.MonitorType;
import com.fuershiye.woman.monitor.service.*;
import com.fuershiye.woman.monitor.utils.*;
import org.apache.commons.lang.StringUtils;
//import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fuershiye.woman.monitor.constants.Massage;
import com.fuershiye.woman.monitor.constants.Rules;
import com.fuershiye.woman.monitor.model.Indicator;
import com.fuershiye.woman.monitor.model.Unit;
import com.google.common.collect.Lists;

/**
 * @author admin
 */
@Controller
@RequestMapping(value = "/indicator")
public class IndicatorController {

	private static final Logger logger = LoggerFactory
			.getLogger(IndicatorController.class);

	@Autowired
	IndicatorTypeService indicatorTypeService;
	@Autowired
	IndicatorService indicatorService;
	@Autowired
	UnitService unitService;
	@Autowired
	BridgeService bridgeService;
	@Autowired
	FormsService formsService;

//	@RequiresPermissions("indicator:view")
	@RequestMapping(value = "/view.do")
	public String view(String show, Model model) {

		List<IdName> allForms = formsService.getAllNames();
		model.addAttribute("allForms", allForms);

		List<IdName> types = indicatorTypeService.getByCondition(null, "", 1);
		model.addAttribute("indicatorTypeNames", types);
		
		List<IdNamePid> names = indicatorService.getAllNames();
		model.addAttribute("indicatorNames", names);
		
		List<Unit> units = unitService.list("", 0);
		model.addAttribute("units", units);

		List<Integer> years = DateFormatUtil.getAreaYears();
		model.addAttribute("years", years);

		model.addAttribute("rules", Rules.getAllIdName());
		model.addAttribute("monitors", MonitorType.getAllIdName());

		List<IdName> allIndicator = Lists.newArrayList();
		for (IdNameCode idNameCode : indicatorService.listAll()) {
			if(idNameCode!=null){
				IdName idName = new IdName();
				idName.setId(idNameCode.getId());
				idName.setName(idNameCode.getCode()+"--"+idNameCode.getName());
				allIndicator.add(idName);
			}
		}
		model.addAttribute("allIndicator", allIndicator);
		
		return "indicator/" + show;
	}

//	@RequiresPermissions("indicator:list")
	@RequestMapping(value = "/list.do")
	@ResponseBody
	public Result getPage(String name, Long formsid, Long type, Integer province, Integer page, Integer pageSize) {

		if(formsid==null||formsid==0 || type==null||type==0){
			return new Result(Massage.ERROR_PARAMETER);
		}
		if(type==-1){
			type=null;
		}

		List<Indicator> list = Lists.newArrayList();
		int total = 0;

		List<Long> indicatorTypes = Lists.newArrayList();
		indicatorTypes.add(type);
		if(province!=null && province==1){
			list = indicatorService.listByCondition(name, formsid, indicatorTypes, province, 1, new Page(page, pageSize));
			total = indicatorService.getTotal(name, formsid, indicatorTypes, province, 1);
		}else if(province!=null && province==0){
			list = indicatorService.listByConditionOppositeProvince(name, formsid, indicatorTypes, 1, 1, new Page(page, pageSize));
			total = indicatorService.getTotalOppositeProvince(name, formsid, indicatorTypes, 1, 1);
		}else{
			list = indicatorService.listByCondition(name, formsid, indicatorTypes, null, 1, new Page(page, pageSize));
			total = indicatorService.getTotal(name, formsid, indicatorTypes, null, 1);
		}
		List<IdName> types = indicatorTypeService.getByCondition(formsid, name, 1);

		List<ViewIndicator> result = Lists.newArrayList();

		if(!list.isEmpty()){
			for (Indicator indicator : list){
				if(indicator==null){
					continue;
				}
				ViewIndicator viewIndicator = ObjectUtil.turnIndicator2View(indicator);
				viewIndicator.setTname(BaseUtil.getNameById(types, indicator.getType()));
				result.add(viewIndicator);
			}
		}

		return new Result(Massage.SUCCESS, new PageResult(result, total));
	}
		
//	@RequiresPermissions("indicator:type")
	@RequestMapping(value = "/sameType.do")
	@ResponseBody
	public Result getSameType(String type, Long formsid, String iname, Integer page, Integer pageSize) {

		if(null==pageSize){
			pageSize=Integer.MAX_VALUE;
		}

		if(MyUtilString.isBlankNull(type)){
			return new Result(Massage.ERROR_PARAMETER);
		}
		if(type.equals("-1") && formsid==null){
			return new Result(Massage.ERROR_PARAMETER);
		}

		List<Indicator> result = Lists.newArrayList();
		if(type.equals("-1")){
			result = indicatorService.listByCondition(iname, formsid, 1, new Page(1, Integer.MAX_VALUE));
		} else{
			List<Long> types = MyUtilString.str2LongByPlaceHolder(type,",");
			for (Long typeid: types) {
//				List<Indicator> listByCondition(String name, Long formsid, Integer monitor, Long type, Integer status, Page page);
//								listByCondition(String name, Long formsid, Integer monitor, Long type, Integer status, Page page)
				result.addAll(indicatorService.listByCondition(iname, formsid, null, typeid, 1, new Page(1, Integer.MAX_VALUE)));
			}
		}

		//  去掉指标名称中的 **
		List<Indicator> resultDelLabel = Lists.newArrayList();
		for (Indicator i : result) {
			if(null!=i){
				i.setName(i.getName().replace("*",""));
				resultDelLabel.add(i);
			}
		}

		return new Result(Massage.SUCCESS, new PageResult(PageUtil.getPageIndicator(new Page(page, pageSize), resultDelLabel), resultDelLabel.size()));
	}

	
	//不做登录限制
//	@RequiresPermissions("indicator:type")
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "/getByType.do")
	@ResponseBody
	public Result getByType(Long formsid, Long type) {
		if(formsid==null||formsid==0||type==null||type==0){
			return new Result(Massage.ERROR_PARAMETER);
		}
		if(type==-1){
			type=null;
		}
		return new Result(Massage.SUCCESS, indicatorService.listIdNameByCondition(null, formsid, type, 1));
	}
	
//	/**
//	 * @param id 要排序的数据
//	 * @param aim 1:升序; 2:降序
//	 * @return
//	 */
////	@RequiresPermissions("indicator:sort")
//	@RequestMapping(value = "/sort.do")
//	@ResponseBody
//	public boolean sort(Long id, Integer aim) {
//
//		if (id == null || (aim != 1 && aim != 2)) {
//			logger.info("IndicatorController sort id null, id:{},aim:{}", id, aim);
//			return false;
//		}
//		Indicator indicator = indicatorService.get(id);
//		if (indicator == null) {
//			logger.error("IndicatorController IndicatorType null, id:{}", id);
//			return false;
//		}
//
//		Indicator top = indicatorService.findBySort(indicator.getSort(), aim, 1);
//		if (top == null) {
//			// 查不到需要交换的对象,则认为交换成功
//			return true;
//		}
//		// 交换序号
//		long temp = indicator.getSort();
//		indicator.setSort(top.getSort());
//		top.setSort(temp);
//		// 保存
//		indicatorService.save(indicator);
//		indicatorService.save(top);
//		return true;
//	}

	@SuppressWarnings("rawtypes")
//	@RequiresPermissions("indicator:save")
	@RequestMapping(value = "/save.do", produces="application/json")
	@ResponseBody
	public Result save(Long id, HttpServletRequest request) {
		
		if(id==null||id==0){
			return addIndicator(request);
		}else{
			return modifyIndicator(id, request);
		}
	}

	//增加新指标
	@SuppressWarnings("rawtypes")
	private Result addIndicator(HttpServletRequest request) {

		//判断code是否存在
		String code = request.getParameter("code");
		if(StringUtils.isBlank(code)){
			return new Result(Massage.ERROR_PARAMETER);
		}

//		//code不可重复并且数据不可删除
//		Indicator indicator = indicatorService.findByCode(code);
//		if(indicator!=null){
//			return new Result(Massage.INDICATOR_EXIST_CODE);
//		}else{
//			indicator = new Indicator();
//		}
		
		Indicator saveIndicator = bridgeService.modifyIndicator(new Indicator(), request);
		indicatorService.save(saveIndicator);

		// 如果是新加的则给默认的排序号sort(主键id)
		Indicator top = indicatorService.getTop();
		if (top != null) {
			saveIndicator.setCtime(new Date());
			saveIndicator.setSort(top.getSort()+1);
			indicatorService.save(saveIndicator);
			return new Result(Massage.SUCCESS);
		} else {
			logger.error("IndicatorController add is null");
			return new Result(Massage.INDICATOR_ADD);
		}
		
	}

	//修改旧指标
	@SuppressWarnings("rawtypes")
	private Result modifyIndicator(Long id, HttpServletRequest request) {
		
		Indicator indicator = indicatorService.get(id);
		if (indicator == null) {
			logger.error("IndicatorController update,IndicatorType is null");
			return new Result(Massage.INDICATOR_IS_NULL);
		}
		
		Indicator saveIndicator = bridgeService.modifyIndicator(indicator, request);
		indicatorService.save(saveIndicator);
		
		return new Result(Massage.SUCCESS);
	}

	//    @RequiresPermissions("indicator:delete")
	@RequestMapping(value="/delete.do")
	@ResponseBody
	public Result delete(Long id) {
		if(id==null||id==0){
			return new Result(Massage.ERROR_PARAMETER);
		}
		Indicator it = indicatorService.get(id);
		if(it==null){
			return new Result(Massage.INDICATOR_IS_NULL);
		}
		it.setStatus(0);//修改为已删除
		indicatorService.save(it);
		return new Result(Massage.SUCCESS);
	}

}
